﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StackExchange.Redis.Extensions.Core;
using StackExchange.Redis.Extensions.Newtonsoft;

namespace SuperJoe.Framework.Caching
{
    public class SERedisCache : IRedisCache
    {
        StackExchangeRedisCacheClient cacheClient = null;

        public SERedisCache(string connectionString)
        {
            cacheClient = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), connectionString);
        }

        #region ICache 接口实现

        public T Get<T>(string key)
        {
            return cacheClient.Get<T>(key);
        }

        public async Task<T> GetAsync<T>(string key)
        {
            return await cacheClient.GetAsync<T>(key);
        }

        public bool Remove(string key)
        {
            return cacheClient.Remove(key);
        }

        public bool Add<T>(string key, T value, TimeSpan? expiresIn = default(TimeSpan?))
        {
            if (expiresIn == null)
            {
                return cacheClient.Add<T>(key, value);
            }
            else
            {
                return cacheClient.Add<T>(key, value, expiresIn.Value);
            }
        }

        public async Task<bool> AddAsync<T>(string key, T value, TimeSpan? expiresIn = default(TimeSpan?))
        {
            if (expiresIn == null)
            {
                return await cacheClient.AddAsync<T>(key, value);
            }
            else
            {
                return await cacheClient.AddAsync<T>(key, value, expiresIn.Value);
            }
        }

        #endregion

        #region IRedisCache接口实现

        public void RemoveAll(IEnumerable<string> keys)
        {
            cacheClient.RemoveAll(keys);
        }

        public async Task<bool> RemoveAsync(string key)
        {
            return await cacheClient.RemoveAsync(key);
        }

        public async Task RemoveAllAsync(IEnumerable<string> keys)
        {
            await cacheClient.RemoveAllAsync(keys);
        }

        #endregion
    }
}
